<template>
  <div>
    <input type="text" v-model="text"><button @click="search()">搜索</button>
    <button @click="sort()">价格从高到低</button>
    <button @click="sort2()">价格从低到高</button>
    <table border="1" style="width: 100%;text-align: center;">
      <thead>
        <tr>
          <th>ID</th>
          <th>名称</th>
          <th>价格</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item,index) in arr2" :key="item.id"  v-highlight-row="index">
          <td>{{item.id}}</td>
          <td>{{item.name}}</td>
          <td>{{item.price}}</td>
          <td><button @click="del(index)">删除</button></td>
        </tr>
      </tbody>
    </table>
  </div>
</template>
<script>
import { reactive,ref } from 'vue'

export default{
  // 自定义属性
  directives: {
    // 定义自定义指令
    'highlight-row': {
      mounted(el, binding) {
        // binding.value 是传递的值（这里是 index）
        const index = binding.value;
        // 偶数行浅灰色，奇数行白色
        el.style.backgroundColor = index % 2 === 0 ? 'red' : 'green';
      },
      updated(el, binding) {
        // 数据更新时重新计算背景色
        const index = binding.value;
        el.style.backgroundColor = index % 2 === 0 ? 'red' : 'green';
      }
    }
  },
  setup(){
    // 输入框的值
    let text = ref()
    // 数据
    let arr = reactive([{
      id:1,
      name:"电视",
      price:100
    },{
      id:2,
      name:"平板",
      price:10
    },{
      id:3,
      name:"手机",
      price:20
    },{
      id:4,
      name:"电脑",
      price:200
    }])
    let arr2 = reactive([...arr])
    // 排序
    function sort(){
      arr2.sort((a,b)=>b.price - a.price)    
    }
    function sort2(){
      arr2.sort((a,b)=>a.price - b.price)  
    }
    // 搜索
    function search(){
      arr2.splice(0,arr.length)
      let filterarr = arr.filter(item => item.name.includes(text.value))
      filterarr.forEach(item => arr2.push(item))
    }
    // 删除
    function del(index){
     arr2.splice(index,1)
    }
    return {arr,sort,sort2,text,search,arr2,del}
  }
}
</script>
